package com.mysum.netty.server;


import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class MessageServerHandler extends SimpleChannelUpstreamHandler {  
   
    private static final Logger logger = Logger.getLogger(  
            MessageServerHandler.class.getName());  
   private static AtomicLong count = new AtomicLong(0);
    @Override  
    public void messageReceived(  
            ChannelHandlerContext ctx, MessageEvent e) {  
        if (!(e.getMessage() instanceof String)) {  
            return;//(1)  
        }  
        String msg = (String) e.getMessage();  
        System.err.println("server got msg:"+msg);  
        e.getChannel().write("server handle result:" + count.incrementAndGet());//(2)  
    }  
   
    @Override  
    public void exceptionCaught(  
            ChannelHandlerContext ctx, ExceptionEvent e) {  
        logger.log(  
                Level.WARN,  
                "Unexpected exception from downstream.",  
                e.getCause());  
        e.getChannel().close();  
    }  
} 